/*
 * Created on Feb 25, 2005
 */
package com.scalar.chiptrack.finance.openpo.actioncommands;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackExtendedAction;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.finance.openpo.forms.PurchaseOrderReceiptForm;
import com.scalar.chiptrack.finance.openpo.*;
import com.scalar.chiptrack.finance.openpo.dao.PurchaseOrderDAO;
import com.scalar.chiptrack.users.ErrorReport;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.ScalarException;

/**
 * @author Ravikanth
**/
public class RecevingLineItemLotDataEntryCloseCommand extends ChipTrackExtendedAction
{

	public ActionForward executeRequest( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
	{
		HashMap errors              = ( HashMap ) request.getAttribute( ERROR_MESSAGES );
		HashMap info                = ( HashMap ) request.getAttribute( INFO_MESSAGES );
		String actionForward 		= "recevingLineItemLotEntry";
		HttpSession mSession 		= request.getSession();
        PurchaseOrderReceiptForm receiptForm = ( PurchaseOrderReceiptForm ) form;
        ReceivingLineItemList receivingLineItemList = receiptForm.getReceivingLineItemList();
		
        try
		{
            if ( ( receiptForm.getPoType() == Constants.PO_TYPE_OPEN ) &&  receiptForm.getOpenPOLotList() != null )
            {
            	Map lotMap = prepareLotMap( receiptForm.getOpenPOLotList() );
                int nextLineItemNo = PurchaseOrderDAO.getPOMaxLineItemNo( null, receiptForm.getPurchaseOrder_Id() ) + 1;
                int listSize = (receiptForm.getReceivingLineItemList() != null ) ? receiptForm.getReceivingLineItemList().size() : 0;
                for ( int i=0; i < listSize; i++ )
                {
                    ReceivingLineItem receivingLineItem = (ReceivingLineItem)receiptForm.getReceivingLineItemList().get(i);
                    if ( nextLineItemNo <= receivingLineItem.getPurchaseOrderLineItemNumber() )
                    {
                        nextLineItemNo = receivingLineItem.getPurchaseOrderLineItemNumber()+1;
                    }
                }

                Iterator processStepsIterator = lotMap.keySet().iterator();
                while ( processStepsIterator.hasNext() )
                {
                    String processStepId = (String)processStepsIterator.next();
                    ReceivingLineItem newReceivingLineItem = new ReceivingLineItem();
                    newReceivingLineItem.setSelected( true );
                    newReceivingLineItem.setProcessStepId( Integer.parseInt ( processStepId ) );
                    newReceivingLineItem.setPurchaseOrderLineItemNumber( nextLineItemNo++ );
                    newReceivingLineItem.setRequestedDate( StringUtils.formatDateToString( new Date() ) );
                    PurchaseOrderLineItemLotDataEntryList processStepLotList = (PurchaseOrderLineItemLotDataEntryList)lotMap.get ( processStepId );
                    
                    newReceivingLineItem.setPurchaseOrderLineItemLotDataEntryList( processStepLotList );
                    int totalLotQty = getTotalQty( processStepLotList );
                    newReceivingLineItem.setRequestedQuantity( totalLotQty );
                    newReceivingLineItem.setShippedQty( totalLotQty );
                    if ( processStepLotList.size() > 0 )
                    {
                        PurchaseOrderLineItemLotDataEntry lot = (PurchaseOrderLineItemLotDataEntry)processStepLotList.get( 0 );
                        newReceivingLineItem.setPartNumber( lot.getPartNumber() );
                        newReceivingLineItem.setProcessName( lot.getPsTypeName() );
                    }
                    if ( receivingLineItemList == null )
                    {
                        receivingLineItemList = new ReceivingLineItemList();
                    }
                    receivingLineItemList.add ( newReceivingLineItem );
                }
                receiptForm.setReceivingLineItemList( receivingLineItemList );
                receiptForm.setOpenPOLotList( null );
            }
            else
            {
                if( receivingLineItemList != null && receivingLineItemList.size() != 0)
                {
                    Iterator lineItemIter = receivingLineItemList.iterator();
                    while( lineItemIter.hasNext() )
                    {
                        ReceivingLineItem recevingLineItem = (ReceivingLineItem) lineItemIter.next();
                        PurchaseOrderLineItemLotDataEntryList purchaseOrderLineItemLotDataEntryList = recevingLineItem.getPurchaseOrderLineItemLotDataEntryList();
                        if( purchaseOrderLineItemLotDataEntryList != null && purchaseOrderLineItemLotDataEntryList.size() != 0 )
                        {
                            Iterator lotDataEntryIter = purchaseOrderLineItemLotDataEntryList.iterator();
                            while( lotDataEntryIter.hasNext() )
                            {
                                PurchaseOrderLineItemLotDataEntry poLineItemDataEntry = ( PurchaseOrderLineItemLotDataEntry ) lotDataEntryIter.next();
                                if ( poLineItemDataEntry != null && ( poLineItemDataEntry.getLotNumber() == null || "".equals(poLineItemDataEntry.getLotNumber().trim())) )
                                {
                                    lotDataEntryIter.remove();
                                }
                            }
                            int totalLotQty = getTotalQty( purchaseOrderLineItemLotDataEntryList );
                            recevingLineItem.setShippedQty( totalLotQty );
                        }
                    }
                }
            }
            actionForward = "recevingLineItemLotEntryClose";
		}
		catch ( Exception e )
		{
            e.printStackTrace();
            Logger.error( "", e );
			errors.put( ERROR_INTERNAL_SERVER_ERROR, "" );
			mSession.setAttribute( ERROR_REPORT_OBJECT, new ErrorReport( "", e ) );
			actionForward = "recevingLineItemLotEntry";
		}

		request.setAttribute( ERROR_MESSAGES, errors );
		request.setAttribute( INFO_MESSAGES, info );
        PurchaseOrderDAO.loadLineItemPrice( null, receiptForm.getReceivingLineItemList() );                
        PurchaseOrderReceiptConfirmCommand.setExtendedPriceAndTotals( receiptForm );
        
        return mapping.findForward( actionForward );
	}

	private Map prepareLotMap( PurchaseOrderLineItemLotDataEntryList lotList ) throws ScalarException
    {
        Map lotMap = new HashMap();
        Map tempMap = new HashMap();
        if ( lotList != null && lotList.size() > 0 )
        {
            int size = lotList.size();
            for ( int i = 0; i < size; i++ )
            {
                PurchaseOrderLineItemLotDataEntry lot = (PurchaseOrderLineItemLotDataEntry)lotList.get( i );
                if ( lot.getProcessStepId() > 0 )
                {
                    if ( tempMap.containsKey( lot.getProcessStepId()+"" ) )
                    {
                        PurchaseOrderLineItemLotDataEntryList processStepLotList = (PurchaseOrderLineItemLotDataEntryList)tempMap.get( lot.getProcessStepId()+"" );
                        processStepLotList.add( lot );
                    }
                    else
                    {
                        PurchaseOrderLineItemLotDataEntryList processStepLotList = new PurchaseOrderLineItemLotDataEntryList();
                        processStepLotList.add ( lot );
                        tempMap.put( lot.getProcessStepId()+"", processStepLotList );
                    }
                    if ( lot.isSelected() )
                    {
                        lotMap.put( lot.getProcessStepId()+"", tempMap.get( lot.getProcessStepId()+"" ) );
                        if ( lot.getLotId() <= 0 )
                        {
                            lot.setPartNumber( ProductDao.getDeviceName( lot.getProcessStepId() ) );
                        }
                    }
                }
            }
        }
        return lotMap;
    }
    private int getTotalQty( PurchaseOrderLineItemLotDataEntryList lotList )
    {
        int totalQty = 0;
        if ( lotList != null && lotList.size() > 0 )
        {
            int size = lotList.size();
            for ( int i = 0; i < size; i++ )
            {
                PurchaseOrderLineItemLotDataEntry lot = (PurchaseOrderLineItemLotDataEntry)lotList.get( i );
                if ( lot.isSelected() )
                {
                    totalQty += lot.getQtyPulled();
                }
            }
        }
        return totalQty;
    }
}
